/* eslint-disable no-await-in-loop */
/* eslint-disable camelcase */
const { Service } = require('egg')
const iconv = require('iconv-lite')
const AipOcrClient = require('baidu-aip-sdk').ocr
const { encodeInp } = require('../utils/encryption')

// 设置APPID/AK/SK
const APP_ID = '20636887'
const API_KEY = 'ZRSVur0vlzuGdv43WKfHfGHe'
const SECRET_KEY = 'VChEpLKDfHZy98EigC7v2nRGQiYGGjmp'

// const APP_ID = '63137349';
// const API_KEY = 'mLESDHq2EZWZCGoaRGxyC9J3';
// const SECRET_KEY = 'oGRAStfdI1NxvWJP5V3ZnNcjgEVm308H';

// 新建一个对象，建议只保存一个对象调用服务接口
const OcrClient = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY)

const getCode = async (ctx) => {
  const apiUrl_verifycode = `${ctx.state.baseUrl}/jsxsd/verifycode.servlet`
  const res_verifycode = await ctx.curl(apiUrl_verifycode, {
    method: 'GET',
    headers: {
      'Content-Type': 'mage/jpeg;charset=utf-8',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
    },
    timeout: 10000,
  })
  const setCookie = res_verifycode.headers['set-cookie'] ? res_verifycode.headers['set-cookie'].map((e) => e.split(';')[0]).join(';') : ''
  const imageBase64 = `data:image/jpeg;base64,${res_verifycode.data.toString('base64')}`
  const result = await OcrClient.generalBasic(imageBase64)
  const code = result.words_result[0].words.toLowerCase().replace(/\s/g, '')
  return { setCookie, code }
}

const login = async (ctx, setCookie, sid, pwd, RANDOMCODE) => {
  const encoded = `${encodeInp(sid)}%%%${encodeInp(pwd)}`
  const apiUrl = `${ctx.state.baseUrl}/jsxsd/xk/LoginToXk`
  const res = await ctx.curl(apiUrl, {
    method: 'POST',
    data: {
      encoded,
      RANDOMCODE,
    },
    headers: {
      Cookie: setCookie,
      'Content-Type': 'application/x-www-form-urlencoded',
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36',
    },
    timeout: 10000,
  })
  console.log('res.status', res.status)
  if (res.status === 200) {
    if (iconv.decode(res.data, 'GBK').includes('验证码错误')) return 0
    return -1
  }
  if (res.status === 302) return 1
  return -1
}

module.exports = class LoginService extends Service {
  /**
   * * 模拟登录，获取cookie
   * @return {setCookie: string, status: number} **
   */
  async getCookie() {
    try {
      const { ctx } = this
      const { sid, pwd } = ctx.data

      let cookie = ''
      for (const i of [1, 2, 3, 4, 5]) {
        console.log('i', i)
        const { setCookie, code } = await getCode(ctx)
        if (code.length !== 4) continue
        const status = await login(ctx, setCookie, sid, pwd, code)
        if (status === 0) continue
        if (status === 1) return { setCookie, status: 302 }
        if (status === -1) return { setCookie, status: 200 }
        cookie = setCookie
      }

      return { setCookie: cookie, status: 402 }
    } catch (err) {
      console.log(err)
      return { setCookie: '', status: 500 }
    }
  }
}
